import React, { Component } from 'react'
import { changeAddress, getList } from '../../actions/index'
import { connect } from 'react-redux'

// 展示组件
class Address extends Component {

    componentDidMount(){
        console.log(this.props)
        // 判断list是否有数据
        if (this.props.list.length <= 0) {
            this.props.setList()
        }
    }

    change = (address, id) => {
        // 修改当前选中地址
        this.props.changeAddress(address, id)
        this.props.history.goBack()
    }

    goEdit = () => {
        this.props.history.push('/edit')
    }

    render() {
        return (
            <div className="wrap address-page">
                <h2>请选择地址</h2>
                <ul>
                    {
                        this.props.list.map(item => {
                            return (
                                <li className={'item' + (item.flag ? ' active' : '')} onClick={() => this.change(item.address, item.id)} key={item.id}>
                                    <p>{item.name}</p>
                                    <p>{item.tel}</p>
                                    <p>{item.address}</p>
                                </li>
                            )
                        })
                    }
                </ul>
                <button onClick={this.goEdit}>新增地址</button>
            </div>
        )
    }
}


// 容期组件 处理和 store 的交互

// 把返回的对象添加到组件的props里
let mapStateToProps = state => {
    return {
        list: state.addressList
    }
}

// 把返回的对象添加到组件的props里
let mapDispatchToProps = dispatch => {
    return {
        setList(){
            dispatch(getList)
        },
        changeAddress(address, id){
            dispatch(changeAddress(address, id));
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Address)